package uform.model.value;

import thx.util.Result;
import thx.error.Error;
using thx.util.Results;

using StringTools;

class StringType extends ValueType<String>
{
	static var _rePhrase = ~/^([^},\]]+)/;
	public function new()
	{
		super();
	}
	
	override function validateType(value : Dynamic) : Result
	{
		if (Std.is(value, String))
			return Result.Ok;
		else
			return "expected type {0} but was {1}".failure(["String", Types.typeName(value) ]);
	}

	override function _parse(s : String, ?ref : { s : String }) : String
	{
		if (null == ref)
		{
			return s.trim();
		}
		s = s.ltrim();
		var q = s.substr(0, 1);
		if (q == '"' || q == "'")
		{
			var pos = 0;
			do {
				pos++;
				var p = s.indexOf(q, pos);
				if (p < 0)
					throw new Error("unable to find ending quote for string value {0:T,20}", s);
				pos = p;
			} while (s.substr(pos - 1, 1) == '\\' && pos < s.length);
			if (null != ref)
				ref.s = s.substr(pos + 1);
			return s.substr(1, pos-1).replace("\\" + q, q);
		} else if (_rePhrase.match(s)) {
			if (null != ref)
				ref.s = _rePhrase.matchedRight();
			return _rePhrase.matched(1);
		} else
			throw new Error("unable to parse string value '{0:T,20}'", s);
	}
	
	override function render(value : String) : String
	{
		return '"' + value.replace('"', '\\"') + '"';
	}
}